<?php
require_once WACT_ROOT . '/db/db.inc.php';
require_once APP_ROOT.'model/common/date.php';
require_once APP_ROOT.'model/common/site.php';

class FormFieldModel {
   // type (0-text single, 1-text multiple, 2-checkbox, 3 - select single, 4 - select multiple, 5 - option
    function &getFieldsTypesList() {
		$typesArray = array('0'=>'Text single line',
							'1'=>'Text multiple lines',
                            '2'=>'Checkbox',
                            '3'=>'Select single selection',
                            '4'=>'Select multiple selection',
                            '5'=>'Radiobutton',
                            '6'=>'Checkboxes group',
                            '7'=>'Radiobuttons group'
							);
		return $typesArray;
	}

    function &getFieldsTypeName($i) {
    	$typesArray =& FormFieldModel::getFieldsTypesList();
    	return $typesArray[$i];
	}

    function &getRecord($field_id) {
        return DBC::FindRecord("SELECT FF.*
        FROM sport_form_fields FF
        WHERE FF.field_id = ". DBC::makeLiteral($field_id));
    }

    function &getOptionsAsArray($options) {
    	$arr = explode(",", $options);
        return $arr;
    }

    function delete($id) {
        DBC::execute("DELETE FROM sport_form_fields WHERE field_id=". DBC::makeLiteral($id));
    }

    function insertField(&$data) {
    	$form_id = $data->get('form_id');
        if ( $form_id ) {
            // get next order
        	$order = FormFieldModel::getNextOrder($form_id);
        	//print 'Next order = '.$order;
        	$data->set('`order`',$order);
        }

        //print_r($data);

        $Record =& DBC::NewRecord($data);
        $field_id =  $Record->insertId('sport_form_fields',
            array('form_id', 'type','options', 'orientation', 'name', 'title',
            '`order`'), 'field_id');
        return $field_id;
  	}

    function updateField($id, &$data) {
        $Record =& DBC::NewRecord($data);
        $Record->update('sport_form_fields',
            array('form_id', 'type','options', 'orientation', 'name', 'title'),
            "field_id=". DBC::makeLiteral($id));
    }

    function &getFormFields($form_id) {
     	$sql = "select FF.*
     	from sport_form_fields FF
        where FF.form_id =". DBC::makeLiteral($form_id)."
     	order by FF.`order` ";
     	//print $sql;
        return DBC::NewRecordSet($sql);
  	}

    // get last order of the fields
    function getLastOrder($form_id) {
    	if (!$form_id) $form_id = 0;
    	$order = 0;

        $rec =& DBC::FindRecord("select max(`order`) as max_order from sport_form_fields
        where form_id = ". DBC::makeLiteral($form_id));
        if ($rec) $order = $rec->get('max_order');
        else  $order=0;
        //print 'Last order for parent_id '.$parent_id.' = '.$order;
        return $order;
    }

    // get order of the field
    function getOrder($field_id) {
    	$order = 0;
    	$rec =& DBC::FindRecord("select `order` from sport_form_fields where field_id = ". DBC::makeLiteral($field_id));
        if ($rec) $order = $rec->get('order');
        return $order;
    }

    // get next order of the form fields for the defined form
    function getNextOrder($form_id) {
    	$next_order = 0;
    	$last_order = FormFieldModel::getLastOrder($form_id);
    	$next_order = $last_order+1;
       	return $next_order;
    }

    function updateFieldOrder($field_id, $order) {
     	$data =& new DataSpace();
     	$data->set('`order`', $order);
        $Record =& DBC::NewRecord($data);
        $Record->update('sport_form_fields', array('`order`'),
            "field_id=". DBC::makeLiteral($field_id));
    }

    // returns the previous record for the given order and form_id
    function &getPrevField($order, $form_id, $current_id) {
    	if ( !$form_id ) $form_id = 0;
        $sql = 'select FF.*  from sport_form_fields FF where FF.form_id = '.DBC::makeLiteral($form_id).'
        and FF.`order` <= '.DBC::makeLiteral($order).'
        and FF.field_id <> '.DBC::makeLiteral($current_id).'
        order by FF.`order` desc';

        $result =& DBC::NewRecordSet($sql);

        $result->reset();
        if ($result->next()) {
        	$data =& $result->export();
        	$data['order'] = $result->get('order');
        }
        else $data = null;
        //print_r( $data );
        return $data;
    }

    // returns the next record for the given order and form_id
    function &getNextField($order, $form_id, $current_id) {
        if ( !$form_id ) $form_id = 0;
        $sql = 'select FF.*  from sport_form_fields FF where FF.form_id = '.DBC::makeLiteral($form_id).'
        and FF.`order` >= '.DBC::makeLiteral($order).'
        and FF.field_id <> '.DBC::makeLiteral($current_id).'
        order by FF.`order` asc';

        $result =& DBC::NewRecordSet($sql);

        $result->reset();
        if ($result->next()) {
        	$data =& $result->export();
        	$data['order'] = $result->get('order');
        }
        else $data = null;
        //print_r( $data );
        return $data;
    }

    function swapFields($field1_id, $order1, $field2_id, $order2) {
    	FormFieldModel::updateFieldOrder($field1_id, $order2);
        FormFieldModel::updateFieldOrder($field2_id, $order1);
    }

    function moveFieldUp($field_id) {
    	$current_field =& FormFieldModel::getRecord($field_id);
    	$current_order = $current_field->get('order');
    	//print  'Current Order: '.$current_order;
    	$form_id = $current_field->get('form_id');
    	$prev_field =&  FormFieldModel::getPrevField($current_order, $form_id, $field_id);
    	//print gettype( $prev_menu );
    	if ($prev_field) {

            $prev_order =  $prev_field['order'];
            //print  'Prev Order: '.$prev_order;
            $prev_field_id = $prev_field['field_id'];
    	}
        if ($prev_field_id) FormFieldModel::swapFields($field_id,$current_order,$prev_field_id,$prev_order);
    }

    function moveFieldDown($field_id) {
    	$current_field =& FormFieldModel::getRecord($field_id);
    	$current_order = $current_field->get('order');
    	$form_id = $current_field->get('form_id');
    	$next_field =&  FormFieldModel::getNextField($current_order, $form_id, $field_id);
    	if ($next_field) {

            $next_order =  $next_field['order'];
            $next_field_id = $next_field['field_id'];
    	}
        if ($next_field_id) FormFieldModel::swapFields($field_id,$current_order,$next_field_id,$next_order);
    }

}

class FormModel {

	function &getFormTypesList() {
		$typesArray = array('0'=>'Article feedback','1'=>'Other');
		return $typesArray;
	}

    function &getFormTypeName($i) {
    	$typesArray =& FormModel::getFormTypesList();
    	return $typesArray[$i];
	}

    function &getRecord($id) {
        return DBC::FindRecord("SELECT F.*
        FROM sport_forms F
        WHERE F.form_id = ". DBC::makeLiteral($id));
    }

    function getPublicURLByID($id) {
        $url = 'form/show.htm?form_id='.$id;
    	if (APP_NAME!='.') $url = '/'.APP_NAME.'/'.$url;
    	else  $url = '/'.$url;
    	return $url;
    	//return '/'.APP_NAME.'/'.'pub.form.php?form_id='.$id;
    }

    function delete($id) {
        DBC::execute("DELETE FROM sport_forms WHERE form_id=". DBC::makeLiteral($id));
        DBC::execute("DELETE FROM sport_form_submissions WHERE form_id=". DBC::makeLiteral($id));
        DBC::execute("DELETE FROM sport_form_fields WHERE form_id=". DBC::makeLiteral($id));
    }

    function &getAllForms() {
    	$site_id = Site::getSiteID();
     	$sql = "select F.*, U.user_id
     	from sport_forms F
     	left outer join sport_users U on F.user_id = U.user_id
        where 1=1  and F.site_id = ".DBC::makeLiteral($site_id)."
     	order by F.title";
     	//print $sql;
        return DBC::NewRecordSet($sql);
  	}

  	function insertForm(&$data) {
  	    $site_id = Site::getSiteID();
  	    $data->set('site_id',$site_id);
        $Record =& DBC::NewRecord($data);
        $form_id =  $Record->insertId('sport_forms',
            array('title', 'type','description', 'after_msg', 'user_id', 'date_added',
            'email_send', 'db_update', 'emails', 'active','site_id'),
            'form_id');
        return $form_id;
  	}

    function updateForm($id, &$data) {
        $site_id = Site::getSiteID();
  	    $data->set('site_id',$site_id);
        $Record =& DBC::NewRecord($data);
        $Record->update('sport_forms',
            array('title', 'type','description', 'after_msg',
            'email_send', 'db_update', 'emails','site_id'),
            "form_id=". DBC::makeLiteral($id));
    }

    function activateForm($id,  &$data, $flag) {
     	if ($flag)  $data->set('active',1);
     	else $data->set('active',0);
        $Record =& DBC::NewRecord($data);
        $Record->update('sport_forms',
            array('active'),
            "form_id=". DBC::makeLiteral($id));
    }


 function &getFeedbackFormsPagedList(&$Pager) {
 		$site_id = Site::getSiteID();
     	$sql = "select F.*, U.*
     	from sport_forms F
     	left outer join sport_users U on F.user_id = U.user_id
        where 1=1 and F.`type`=0
        and F.site_id = ".DBC::makeLiteral($site_id)."
     	order by F.title";
     	//print $sql;
        return DBC::NewPagedRecordSet($sql, $Pager);
  }

  function &getFeedbackForms() {
        $site_id = Site::getSiteID();
     	$sql = "select F.*, U.user_id
     	from sport_forms F
     	left outer join sport_users U on F.user_id = U.user_id
        where 1=1 and F.`type`=0
        and F.site_id = ".DBC::makeLiteral($site_id)."
     	order by F.title";
     	//print $sql;
        return DBC::NewRecordSet($sql);
  }


  function &getFeedbackFormsForCombo() {
  		$rs =& FormModel::getFeedbackForms();
        $rs->reset();
        $list = array();
        while($rs->next()) {
        	$form_id = $rs->get('form_id');
            $title = $rs->get('title');
            $list[$form_id] = $title;
        }
        return $list;
  }


}

class SubmissionFormField {
	function insertSubmissionField(&$data) {
        $Record =& DBC::NewRecord($data);
        $id =  $Record->insertId('sport_form_submission_fields',
            array('submission_id', 'field_id','value'),
            'id');
        return $id;
  	}
}

class SubmissionForm {

	function insertSubmission(&$data) {
		$data->set('new',1);
        $Record =& DBC::NewRecord($data);
        $submission_id =  $Record->insertId('sport_form_submissions',
            array('user_id', 'form_id','date', 'article_id', 'new'),
            'submission_id');
        return $submission_id;
  	}

    function &getRecord($id) {
        return DBC::FindRecord(
        "SELECT S.*, F.*, U.*, A.*, F.`title` as form_header,
        C1.`name` as category1, C2.`name` as category2
        FROM sport_form_submissions S
        inner join sport_forms F
        on S.form_id = F.form_id
        left outer join sport_users U
        on S.user_id = U.user_id
        inner join sport_articles A
        on S.article_id = A.article_id
        left outer join sport_categories C1
     	on A.category_id = C1.category_id
        left outer join sport_categories C2
     	on A.category2_id = C2.category_id
        WHERE S.submission_id=". DBC::makeLiteral($id));
    }

    function delete($id) {
        DBC::execute("DELETE FROM sport_form_submissions WHERE submission_id=". DBC::makeLiteral($id));
        DBC::execute("DELETE FROM sport_form_submission_fields WHERE submission_id=". DBC::makeLiteral($id));
    }

    function &getFeedbackFields($submission_id) {
    	$sql = "select SFI.*, FI.*
    	from sport_form_submission_fields SFI
    	inner join sport_form_fields FI
    	on SFI.field_id = FI.field_id
    	where SFI.submission_id = ". DBC::makeLiteral($submission_id);
    	//print $sql;
    	return DBC::NewRecordSet($sql);

    }

    function getFeedbacksCount($user_id) {
    	$site_id = Site::getSiteID();
    	return DBC::getOneValue("Select count(*)
    		from sport_form_submissions S
     		inner join sport_forms F
     		on S.form_id = F.form_id
     		left outer join sport_users U
     		on S.user_id = U.user_id
     		inner join sport_articles A
     		on S.article_id = A.article_id
    		where F.site_id = ".DBC::makeLiteral($site_id)."
           	and user_id=".DBC::makeLiteral($user_id));
    }

    function getNewFeedbacksCount() {
    	$site_id = Site::getSiteID();
    	return DBC::getOneValue("Select count(*)
    	from sport_form_submissions S
     	inner join sport_forms F
     	on S.form_id = F.form_id
     	left outer join sport_users U
     	on S.user_id = U.user_id
     	inner join sport_articles A
     	on S.article_id = A.article_id
    	where  F.site_id = ".DBC::makeLiteral($site_id)."
        and S.`new`=1 ");
    }

	function &getFeedbacksPagedList(&$Pager, &$request, &$responseModel) {
    	//restore filter from session
     	Session::loadResponseModel($responseModel,'filter.feedbacks');
        $site_id = Site::getSiteID();
     	$sql = "select S.*, F.*, U.*, A.*, C1.`name` as category1, C2.`name` as category2,
     	F.`title` as form_header
     	from sport_form_submissions S
     	inner join sport_forms F
     	on S.form_id = F.form_id
     	left outer join sport_users U
     	on S.user_id = U.user_id
     	inner join sport_articles A
     	on S.article_id = A.article_id
     	left outer join sport_categories C1
     	on A.category_id = C1.category_id
        left outer join sport_categories C2
     	on A.category2_id = C2.category_id
        where 1=1 and F.site_id = ".DBC::makeLiteral($site_id)." ".
        SubmissionForm::getFeedbacksFilter($request, $responseModel)."
     	order by ".SubmissionForm::getFeedbacksOrder($request, $responseModel);
     	//print $sql;
        return DBC::NewPagedRecordSet($sql, $Pager);
  	}

    function getFeedbacksFilter(&$request, &$responseModel) {
      	$where = '';
      	$filter_article_id = $responseModel->get('filter_article_id');
        $article_id = $responseModel->get('article_id');
      	if ($filter_article_id)  $where .= ' and A.article_id = '.DBC::makeLiteral($article_id);

        $filter_headline = $responseModel->get('filter_headline');
        $headline = $responseModel->get('headline');
        if ($filter_headline)  $where .= ' and '.DBC::makeLiteral($headline).'like A.headline ';

        $filter_category1 = $responseModel->get('filter_category1');
        $category1 = $responseModel->get('category1');
        if ($filter_category1)  $where .= ' and A.category_id = '.DBC::makeLiteral($category1);

        $filter_category2 = $responseModel->get('filter_category2');
        $category2 = $responseModel->get('category2');
        if ($filter_category2)  $where .= ' and A.category2_id = '.DBC::makeLiteral($category2);

        $filter_author = $responseModel->get('filter_author');
        $author = $responseModel->get('author');
        if ($filter_author)  $where .= ' and A.author_user_id = '.DBC::makeLiteral($author);

        $filter_user = $responseModel->get('filter_user');
        $user_id = $responseModel->get('user_id');
        if ($filter_user)  $where .= ' and S.user_id = '.DBC::makeLiteral($user_id);

        $filter_form = $responseModel->get('filter_form');
        $form_id = $responseModel->get('form_id');
        if ($filter_form)  $where .= ' and S.form_id = '.DBC::makeLiteral($form_id);

        $filter_start_date = $responseModel->get('start_date_filter');
        $start_day = $responseModel->get('start_day');
        $start_month = $responseModel->get('start_month');
        $start_year = $responseModel->get('start_year');
        $start_date = gmmktime(0, 0, 0, $start_month, $start_day, $start_year);
        $tz =& new MyTimeZone();
        $start_date = $tz->timeLocal( $start_date );
        if ($filter_start_date) $where .= " and S.`date`>='".gmdate("Y.m.d",$start_date)."'";

        $filter_end_date = $responseModel->get('end_date_filter');
        $end_day = $responseModel->get('end_day');
        $end_month = $responseModel->get('end_month');
        $end_year = $responseModel->get('end_year');
        $end_date = gmmktime(0, 0, 0, $end_month, $end_day, $end_year);
        $end_date = $tz->timeLocal( $end_date );
        if ($filter_end_date) $where .= " and S.`date`<='".gmdate("Y.m.d",$end_date)."'";

        $filter_recent = $responseModel->get('recent_filter');
        $recent = $responseModel->get('recent');
        if ($recent) {
        	$start_date = gmmktime(0, 0, 0, gmdate("m"), gmdate("d")-$recent, gmdate("Y"));
        	$start_date = $tz->timeLocal( $start_date );
        }
        if ($filter_recent) $where .= " and S.`date`>='".gmdate("Y.m.d",$start_date)."'";


        return $where;
      }

      function getFeedbacksOrder(&$request, &$responseModel) {
      	$sortby = 'S.date desc';
      	$sortby = $responseModel->get('sort');
      	if ($sortby) return $sortby;
      	else return 'S.date desc';
      }

      function &getNewFeedbacksPagedList(&$Pager, &$request, &$responseModel) {
        $site_id = Site::getSiteID();
        $sql = " select S.*, F.*, U.*, A.*, C1.`name` as category1, C2.`name` as category2,
     	F.`title` as form_header
     	from sport_form_submissions S
     	inner join sport_forms F
     	on S.form_id = F.form_id
     	left outer join sport_users U
     	on S.user_id = U.user_id
     	inner join sport_articles A
     	on S.article_id = A.article_id
     	left outer join sport_categories C1
     	on A.category_id = C1.category_id
        left outer join sport_categories C2
     	on A.category2_id = C2.category_id
        where 1=1 and S.`new` = 1  and
        F.site_id = ".DBC::makeLiteral($site_id)."
     	order by S.`date` desc ";
     	//print $sql;
        return DBC::NewPagedRecordSet($sql, $Pager);
  	  }

      function publishFeedback($id) {
        $data = new DataSpace();
        $data->set('new',0);
    	$Record =& DBC::NewRecord($data);
        $Record->update('sport_form_submissions',
            array('new'),
            "submission_id=". DBC::makeLiteral($id));
      }

      function unpublishFeedback($id) {
        $data = new DataSpace();
        $data->set('new',1);
    	$Record =& DBC::NewRecord($data);
        $Record->update('sport_form_submissions',
            array('new'),
            "submission_id=". DBC::makeLiteral($id));
      }

      // get the next new feedback
    function &getNextNewFeedback($current_submission_id) {
        $site_id = Site::getSiteID();
        $sql = "select A.* from sport_form_submissions A, sport_form_submissions A2,
        sport_forms F, sport_forms F2
        where  A.form_id = F.form_id and A2.form_id = F2.form_id and
        A.submission_id <> A2.submission_id
        and A2.submission_id = ".DBC::makeLiteral($current_submission_id)."
        and A.`date` <= A2.`date`
        and A.`new` = 1
        and F.site_id = ".DBC::makeLiteral($site_id)." "."
        and F2.site_id = ".DBC::makeLiteral($site_id)." "."
        order by A.`date` desc limit 1";
        return DBC::FindRecord($sql);
    }

}


?>